import re
import json
from utils import list_all_files, yaml_to_dict, dict_to_yaml


def load_json_file(file_path: str) -> dict | list | None:
    """
    加载JSON文件并返回其内容
    参数:
        file_path (str): JSON文件的路径
    返回:
        dict | list | None: 解析后的JSON数据，如果出错则返回None
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            pattern = r'```json\s*([\s\S]*?)\s*```'
            match = re.search(pattern, content, re.DOTALL)
            if match:
                json_text = match.group(1).strip()
                data = json.loads(json_text)
            else:
                data = json.loads(content)
            return data
    except FileNotFoundError:
        print(f"错误: 文件 '{file_path}' 不存在")
    except json.JSONDecodeError as e:
        print(f"错误: 文件 '{file_path}' 不是有效的JSON格式")
        print(f"解析错误: {e}")
    except PermissionError:
        print(f"错误: 没有权限读取文件 '{file_path}'")
    except Exception as e:
        print(f"未知错误: {e}")

    return None

def extract_rules(rule_path, save_path):
    res = list_all_files(rule_path)
    map = {}
    for item in res:
        json_text = load_json_file(item)
        print(item)
        for key in json_text:
            if key not in map:
                map[key] = []
            for value in json_text[key]:
                if isinstance(value, dict):
                    if 'rule' in value.keys():
                        map[key].append(value['rule'])
                    if '规则编号' in value.keys():
                        map[key].append(value['规则编号'])
                if isinstance(value, str):
                    map[key].append(value)

    with open(save_path, 'w', encoding='utf-8') as file:
        json.dump(map, file, ensure_ascii=False, indent=4)





